package kr.ltkblue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;

public class GoogleDriveTest {

	  private static String CLIENT_ID = "";
	  private static String CLIENT_SECRET = "";

	  private static String REDIRECT_URI = "http://localhost";

	static	DefaultHttpClient httpclient = new DefaultHttpClient();

	  public static void main(String[] args) throws IOException {
	    HttpTransport httpTransport = new NetHttpTransport();
	    JsonFactory jsonFactory = new JacksonFactory();

	    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
	        httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
	        .setAccessType("online")
	        .setApprovalPrompt("auto").build();

	    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
	    System.out.println("Please open the following URL in your browser then type the authorization code:");
	    System.out.println("  " + url);

	    String loginUrl ="https://www.google.com/accounts/ClientLogin";
	    login(loginUrl);
	    String ddUrl = getPage(url);
	    getPage2(ddUrl);
	    //키보드 입력
//	    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//
//		Document doc = Jsoup.connect(url).get();
//		Elements titles = doc.select("ul#sub_map  li  a");
//
//		//print all titles in main page
//		for(Element e: titles){
//			System.out.println("text: " +e.text());
//			System.out.println("text: " +e.text().substring(0,2));
////			System.out.println("html: "+ e.html());
//		}
//

//	    String code = br.readLine();
	    String code = "";

	    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
	    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

	    //Create a new authorized API client
	    Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

	    //Insert a file
	    File body = new File();
	    body.setTitle("My document");
	    body.setDescription("A test document");
	    body.setMimeType("text/plain");

		URL fileUrl =  ClassLoader.getSystemResource("./");
		java.io.File baseDir = new java.io.File(fileUrl.getFile());

	    java.io.File fileContent = new java.io.File(baseDir,"testFile.txt");
	    FileContent mediaContent = new FileContent("text/plain", fileContent);

	    File file = service.files().insert(body, mediaContent).execute();
	    System.out.println("File ID: " + file.getId());
	  }

	  public static void getHtml(String strUrl) {
		  URL url         = null;
		  StringBuffer sbHtml     = new StringBuffer();
		  BufferedReader br      = null;
		  String data        = null;
		  URLConnection urlc     = null;
		  try{
		   url = new URL(strUrl);
		   urlc = (HttpURLConnection)url.openConnection();
		   urlc.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2)");
		   urlc.setRequestProperty("Accept-Language", "UTF-8");
		   urlc.setRequestProperty("Method", "GET");
		   urlc.setRequestProperty("Accept", "image/gif, image/xxbitmap, image/jpeg, image/pjpeg,application/xshockwaveflash, application/vnd.msexcel,application/vnd.mspowerpoint, application/msword, */*");
		   urlc.setRequestProperty("Accept-Charset","UTF-8");
		   urlc.setConnectTimeout(30000);
		   urlc.setReadTimeout(30000);


		   br = new BufferedReader(new InputStreamReader(urlc.getInputStream(), "UTF-8"));

		   while((data = br.readLine()) != null ){
		    sbHtml.append(data);
		   }

		  }catch (Exception e) {
		   // TODO: handle exception
		   e.printStackTrace();
		  }
		 }

	public static void login(String strUrl) throws ClientProtocolException, IOException {


		// url
		HttpPost httpPost = new HttpPost(strUrl);
		// 파라메터 리스트
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		// 파라메터 설정
		// new BasicNameValuePair(키, 값)

		nvps.add(new BasicNameValuePair("Email", "ltkblue@gmail.com	"));
		nvps.add(new BasicNameValuePair("Passwd", "dorian77"));
		nvps.add(new BasicNameValuePair("accountType", "GOOGLE"));
		nvps.add(new BasicNameValuePair("source", "Google-cURL-Example"));
		nvps.add(new BasicNameValuePair("service", "ac2dm"));

		httpPost.setEntity(new UrlEncodedFormEntity(nvps));

		// 응답
		HttpResponse response = httpclient.execute(httpPost);

		try {
			// 응답 결과
			System.out.println(response.getStatusLine());
			System.out.println("----------------------------------------");

			HttpEntity entity = response.getEntity();

			if (entity != null) {
				System.out.println("Response content length: "
						+ entity.getContentLength());

				// 콘텐츠를 읽어들임.
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						entity.getContent()));

				String line = "";
				while ((line = rd.readLine()) != null) {
					// 콘텐츠 내용
					System.out.println(line);
				}
			}

			// EntityUtils.consume(entity);
		} finally {
			// httpPost.releaseConnection();
		}
	}

	public static String getPage(String strUrl) throws ClientProtocolException, IOException {


		// url
		HttpPost httpPost = new HttpPost(strUrl);
		// 파라메터 리스트
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		// 파라메터 설정
		// new BasicNameValuePair(키, 값)
//
//		nvps.add(new BasicNameValuePair("Email", "ltkblue@gmail.com	"));
//		nvps.add(new BasicNameValuePair("Passwd", "dorian77"));
//		nvps.add(new BasicNameValuePair("accountType", "GOOGLE"));
//		nvps.add(new BasicNameValuePair("source", "Google-cURL-Example"));
//		nvps.add(new BasicNameValuePair("service", "ac2dm"));

		httpPost.setEntity(new UrlEncodedFormEntity(nvps));

		// 응답
		HttpResponse response = httpclient.execute(httpPost);
		StringBuffer sb = new StringBuffer();
		String retVal="";
		try {
			// 응답 결과
			System.out.println(response.getStatusLine());
			System.out.println("----------------------------------------");

			HttpEntity entity = response.getEntity();

			if (entity != null) {
				System.out.println("Response content length: "
						+ entity.getContentLength());

				// 콘텐츠를 읽어들임.
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						entity.getContent()));

				String line = "";
				while ((line = rd.readLine()) != null) {
					// 콘텐츠 내용
					System.out.println(line);
					sb.append(line);
				}
			}
			Document doc = Jsoup.parse(sb.toString());
			Elements titles = doc.select("a");

			//print all titles in main page
			for(Element e: titles){
				System.out.println("text: " +e.text());
				System.out.println("href: " +e.attr("href"));
				retVal=e.attr("href");
//				System.out.println("html: "+ e.html());
			}

//			Document doc = Jsoup.connect(url).get();
//			Elements titles = doc.select("ul#sub_map  li  a");
	//
//			//print all titles in main page
//			for(Element e: titles){
//				System.out.println("text: " +e.text());
//				System.out.println("text: " +e.text().substring(0,2));
////				System.out.println("html: "+ e.html());
//			}
	//

			// EntityUtils.consume(entity);
		} finally {
			// httpPost.releaseConnection();
		}
		return retVal;
	}

	public static String getPage2(String strUrl) throws ClientProtocolException, IOException {


		// url
		HttpPost httpPost = new HttpPost(strUrl);
		// 파라메터 리스트
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		// 파라메터 설정
		// new BasicNameValuePair(키, 값)
//
//		nvps.add(new BasicNameValuePair("Email", "ltkblue@gmail.com	"));
//		nvps.add(new BasicNameValuePair("Passwd", "dorian77"));
//		nvps.add(new BasicNameValuePair("accountType", "GOOGLE"));
//		nvps.add(new BasicNameValuePair("source", "Google-cURL-Example"));
//		nvps.add(new BasicNameValuePair("service", "ac2dm"));

		httpPost.setEntity(new UrlEncodedFormEntity(nvps));

		// 응답
		HttpResponse response = httpclient.execute(httpPost);
		StringBuffer sb = new StringBuffer();
		String retVal="";
		try {
			// 응답 결과
			System.out.println(response.getStatusLine());
			System.out.println("----------------------------------------");

			HttpEntity entity = response.getEntity();

			if (entity != null) {
				System.out.println("Response content length: "
						+ entity.getContentLength());

				// 콘텐츠를 읽어들임.
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						entity.getContent()));

				String line = "";
				while ((line = rd.readLine()) != null) {
					// 콘텐츠 내용
					System.out.println(line);
					sb.append(line);
				}
			}
			// EntityUtils.consume(entity);
		} finally {
			// httpPost.releaseConnection();
		}
		return retVal;
	}
}
